package com.gxuwz.stats.service.excelNewHandler;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.gxuwz.stats.entity.ResearchProject;
import com.gxuwz.stats.entity.dto.ResearchProjectHorizontalDTO;
import com.gxuwz.stats.service.excelhandler.ImportResultProvider;
import com.gxuwz.stats.service.impl.ResearchProjectServiceImpl;

import java.util.ArrayList;
import java.util.List;

public class ResearchProjectHorizontalListener extends AnalysisEventListener<ResearchProjectHorizontalDTO> implements ImportResultProvider {
    private final List<ResearchProject> dataList = new ArrayList<>();
    private final ResearchProjectServiceImpl workloadService;
    private final String currentUsername, currentRole, currentDepartment;
    private int ignoredCount = 0;
    private boolean stopProcessing = false;

    public ResearchProjectHorizontalListener(ResearchProjectServiceImpl workloadService, String username, String role, String department) {
        this.workloadService = workloadService;
        this.currentUsername = username;
        this.currentRole = role;
        this.currentDepartment = department;
    }

    @Override
    public void invoke(ResearchProjectHorizontalDTO dto, AnalysisContext context) {
        if (stopProcessing) return;
        if (dto.getUsername() == null || dto.getUsername().trim().isEmpty()) return;
        if (dto.getUsername().contains("说明") || dto.getUsername().length() > 12) {
            stopProcessing = true;
            return;
        }
        if ("普通用户".equals(currentRole) && !dto.getUsername().equals(currentUsername)) {
            ignoredCount++;
            return;
        }
        // DTO转实体
        ResearchProject entity = new ResearchProject();
        entity.setUsername(dto.getUsername());
        entity.setProjectName(dto.getProjectName());
        entity.setProjectCategory(dto.getProjectCategory());
        entity.setProjectFunding(dto.getProjectFunding() != null ? Double.valueOf(dto.getProjectFunding()) : 0.0);
        entity.setProjectLevel("横向"); // 横向项目直接写死
        entity.setProjectYear(dto.getProjectYear());
        entity.setProjectEndYear(dto.getProjectEndYear());
        // 其它字段可按需补充
        dataList.add(entity);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        workloadService.saveAllFromDTO(dataList);
    }

    @Override
    public int getImportedCount() { return dataList.size(); }
    @Override
    public int getIgnoredCount() { return ignoredCount; }
}
